package com.hancheng.commoncloud.framework.config;

import cn.hutool.core.util.StrUtil;
import com.hancheng.commoncloud.framework.contant.Constants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.seata.core.context.RootContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign远程调用过程中请求头数据传递
 */
@Configuration
public class FeignTokenInterceptor implements RequestInterceptor {

    /**
     * 传递请求头
     *
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        // 从当前线程中获取请求上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        if (requestAttributes instanceof ServletRequestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            String token = request.getHeader(Constants.AUTH_TOKEN);

            // 如果 token 存在，就添加到 Feign 请求头中
            if (StrUtil.isNotBlank(token)) {
                template.header(Constants.AUTH_TOKEN, token);
            }
        }
    }
}
